/*
 * GuildFraktionInfo - list the reputation and the guild level of all members of a wow guild
 * Copyright (C) [2012 - 2013] [www.marantis.de]
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public 
 * License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later 
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied 
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if not, 
 * see <http://www.gnu.org/licenses/>.
 */
package de.marantis.app.wow.gfi.helper;

import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.log4j.Logger;

public class HttpHelper {

    private final static Logger log = Logger.getLogger(HttpHelper.class);

    /**
     * get the content of a webpage.
     *
     * we use 100 KB as buffer size. this will be enough for the most pages.
     *
     */
    public static String getHttpContent(URL aUrl) {

        long t1 = System.currentTimeMillis();
        StringBuffer status = new StringBuffer("");
        
        HttpURLConnection con = null;

        try {
            if (aUrl == null) {
                return null;
            }

            con = (HttpURLConnection)aUrl.openConnection();
            if (con == null) {
                return null;
            }
            
            if (log.isDebugEnabled()){
                long t2 = System.currentTimeMillis();
                t2 = t2 - t1;
                status.append("http: open = ");
                status.append(t2);
                status.append("ms");
            }
            
            con.disconnect();
            con.setUseCaches(false);
            con.setDefaultUseCaches(false);
            con.setConnectTimeout(20 * 1000); // 20 sec timeout
            con.setInstanceFollowRedirects(true);
            con.setRequestMethod("GET");
            con.connect();
            
            if (log.isDebugEnabled()){
                long t2 = System.currentTimeMillis();
                t2 = t2 - t1;
                status.append(", connect = ");
                status.append(t2);
                status.append("ms");
            }
            
            int responseCode = con.getResponseCode();
            if (responseCode >= 400){
                return null;
            }

            final char[] buffer = new char[100 * 1024]; // 100 KB page-buffer
            StringBuilder out = new StringBuilder();
            Reader r = new InputStreamReader(con.getInputStream(), "UTF-8");
            int read;
            do {
                read = r.read(buffer, 0, buffer.length);
                if (read > 0) {
                    out.append(buffer, 0, read);
                }
            } while (read >= 0);

            if (log.isDebugEnabled()){
                long t2 = System.currentTimeMillis();
                t2 = t2 - t1;
                status.append(", read = ");
                status.append(t2);
                status.append("ms");
            }
            
            closeConnection(con);

            //*** if EMPTY then NULL ***
            String content = out.toString();
            content = CommonHelper.Trim2Null(content);
            return content;

        } catch (Exception e) {
            log.error(e);
            return null;
            
        } finally {
            closeConnection(con);
            
            if (log.isDebugEnabled()){
                long t2 = System.currentTimeMillis();
                t2 = t2 - t1;
                status.append(", disc = ");
                status.append(t2);
                status.append("ms");
                
                log.debug(status.toString());
            }
        }
    }

    private static void closeConnection(HttpURLConnection con) {
        try {
            if (con == null) {
                return;
            }

            con.disconnect();

        } catch (Exception e) {
            //nothing to do
        }
    }
}
